package com.ql.mangersystem.utils;


import com.ql.mangersystem.mapper.UserMapper;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class UserUtil {

    public static final String CHARACTERS ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public static final int USERNAME_LENGTH=8;
    public static final String USERNAME_PREFIX="用户_";
    private static final UserMapper userMapper=SpringContextUtils.getBean(UserMapper.class);
    //随机生成字符串
    private static String generateRandomString() {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder(USERNAME_LENGTH);
        for (int i=0;i<USERNAME_LENGTH;i++) {
            int randomIndex =random.nextInt(CHARACTERS.length());
            stringBuilder.append(CHARACTERS.charAt(randomIndex));
        }
        stringBuilder.insert(0,USERNAME_PREFIX);
        return stringBuilder.toString();
    }
    //查询用户名是否存在
    private static boolean isUsernameExist(String username) {
        Integer exists = userMapper.exists(username);
        if (exists==null) {
            return false;
        }
        return true;
    }
    public static String generateUniqueUsername() {
        String s = generateRandomString();
        while (isUsernameExist(s)) {
            s = generateRandomString();
        }

        return s;
    }
}
